package com.project.pet.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.project.pet.common.Constant;
import com.project.pet.mapper.WxUserMapper;
import com.project.pet.pojo.Star;
import com.project.pet.pojo.User;
import com.project.pet.common.ResponseData;
import com.project.pet.mapper.UserMapper;
import com.project.pet.pojo.UserDetailsImpl;
import com.project.pet.pojo.WxUser;
import com.project.pet.utils.JwtTokenUtils;
import com.project.pet.utils.ResponseDataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;


import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService implements UserDetailsService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Value("${wx.appid}")
    private String appid;

    @Value(("${wx.secret}"))
    private String secret;

    @Autowired
    private HttpServletRequest request;

    public ResponseData<Object> selectByPrimaryKey(Integer id){
        return ResponseDataUtil.buildSuccess(userMapper.selectByPrimaryKey(id));
    }

    public ResponseData<Object> selectOne(User user){
        return ResponseDataUtil.buildSuccess(userMapper.selectOne(user));
    }

    public ResponseData<Object> select(User user){
        return ResponseDataUtil.buildSuccess(userMapper.select(user));
    }

    public ResponseData<Object> selectAll(){
        return ResponseDataUtil.buildSuccess(wxUserMapper.selectAll());
    }

    public ResponseData<Object> selectByExample(HashMap<String,Object> map){
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        for(Map.Entry<String, Object> entry : map.entrySet()){
            String key = entry.getKey();
            Object value = entry.getValue();
            criteria.andEqualTo(key,value);
        }
        return ResponseDataUtil.buildSuccess(userMapper.selectByExample(example));
    }

    public ResponseData<Object> pagingQuery(HashMap<String,Object> map){
        Integer pageIndex = Integer.parseInt(map.get("pageIndex").toString());
        Integer pageSize = Integer.parseInt(map.get("pageSize").toString());
        map.remove("pageIndex");
        map.remove("pageSize");
        Example example = new Example(WxUser.class);
        Example.Criteria criteria = example.createCriteria();
        for(Map.Entry<String, Object> entry : map.entrySet()){
            String key = entry.getKey();
            Object value = entry.getValue();
            if(!StringUtils.isEmpty(value))
                criteria.andLike(key,"%"+value+"%");
        }
        PageHelper.startPage(pageIndex,pageSize);
        List<WxUser> userList = wxUserMapper.selectByExample(example);
        PageInfo<WxUser> pageInfo = new PageInfo<WxUser>(userList);
        return ResponseDataUtil.buildSuccess(pageInfo);
    }

    public ResponseData<Object> insertSelective(User user){
        return userMapper.insertSelective(user)>0? ResponseDataUtil.buildSuccess(): ResponseDataUtil.buildError("插入数据失败");
    }

    public ResponseData<Object> updateByPrimaryKey(User user){
        return userMapper.updateByPrimaryKey(user)>0? ResponseDataUtil.buildSuccess(): ResponseDataUtil.buildError("更新数据失败");
    }

    public ResponseData<Object> deleteByPrimaryKey(Integer id){
        return userMapper.deleteByPrimaryKey(id)>0? ResponseDataUtil.buildSuccess(): ResponseDataUtil.buildError("删除数据失败");
    }

    @Transactional
    public ResponseData<Object> delete(List<Integer> ids){
        try{
            for (Integer id : ids) {
                userMapper.deleteByPrimaryKey(id);
            }
            return ResponseDataUtil.buildSuccess();
        }catch (Exception e){
            return ResponseDataUtil.buildError("删除数据失败");
        }
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",username);
        List<User> users = userMapper.selectByExample(example);
        if(!users.isEmpty()){
            User user = users.get(0);
            return new UserDetailsImpl(user);
        }
        else
            throw new UsernameNotFoundException("登录用户不存在");
    }

    public ResponseData<Object> webRegister(User user){
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String password = bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(password);
        try{
            userMapper.insertSelective(user);
            return ResponseDataUtil.buildSuccess("添加用户成功");
        }catch (DuplicateKeyException e){
            return ResponseDataUtil.buildError("用户名已存在");
        }
    }
    public ResponseData<Object> webUpdate(User user){
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",user.getUsername());
        List<User> users = userMapper.selectByExample(example);
        if(!users.isEmpty()){
            User us = users.get(0);
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String password = bCryptPasswordEncoder.encode(user.getPassword());
            us.setPassword(password);
            userMapper.updateByPrimaryKeySelective(us);
            return ResponseDataUtil.buildSuccess("修改密码成功");
        }
        else{
            return ResponseDataUtil.buildError("用户名不存在");
        }

    }

    public ResponseData<Object> wxLogin(String code, WxUser wxUser){
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
        JSONObject jsonObject = JSONObject.parseObject(HttpUtil.get(url));
        //拿到微信用户的openid
        if(jsonObject.containsKey("openid")){
            String openid = String.valueOf(jsonObject.get("openid"));
            wxUser.setOpenid(openid);
            Example example = new Example(WxUser.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("openid",openid);
            List<WxUser> wxUsers = wxUserMapper.selectByExample(example);
            Integer wxUserId = 0;
            // 如果不存在，则插入到系统里
            if(wxUsers.isEmpty()){
                wxUser.setAvatarUrl(Constant.DEFAULT_AVATAR_PATH);
                wxUserMapper.insert(wxUser);
                wxUserId = wxUserMapper.selectByExample(example).get(0).getId();
            }else{
                wxUserId = wxUsers.get(0).getId();
//                wxUser.setId(wxUserId);
//                wxUserMapper.updateByExample(wxUser,example);
                wxUser =  wxUsers.get(0);
            }
            Map<String, Object> map = new HashMap<>();
            String token = jwtTokenUtils.generateToken(wxUserId, map);
            map.put("token",token);
            map.put("wxUSerId",wxUserId);
            map.put("openid",openid);
            map.put("wxUser",wxUser);
            return ResponseDataUtil.buildSuccess(map);
        }else{
            return ResponseDataUtil.buildError("无法获取登陆信息");
        }
    }

    public ResponseData<Object> findById() {
        Integer wxId = Integer.parseInt(request.getAttribute("wxUserId").toString());
        return ResponseDataUtil.buildSuccess(wxUserMapper.selectByPrimaryKey(wxId));
    }

    public ResponseData<Object> updateByPrimaryKey(WxUser wxUser){
        wxUser.setId(Integer.parseInt(request.getAttribute("wxUserId").toString()));
        int res = wxUserMapper.updateByPrimaryKeySelective(wxUser);
        return res>0? ResponseDataUtil.buildSuccess("操作成功"): ResponseDataUtil.buildError("操作失败");
    }


    public ResponseData<Object> wxUserIfRegister(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        JSONObject jsonObject = JSONObject.parseObject(HttpUtil.get(url));
        System.out.println(jsonObject);
        if (jsonObject.containsKey("openid")) {
            String openid = String.valueOf(jsonObject.get("openid"));
            WxUser wxUser = new WxUser();
            wxUser.setOpenid(openid);
            Example example = new Example(WxUser.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("openid", openid);
            List<WxUser> wxUsers = wxUserMapper.selectByExample(example);
            if (wxUsers.isEmpty()) {
                return ResponseDataUtil.buildSuccess(0);
            } else {
                return ResponseDataUtil.buildSuccess(1);
            }
        } else {
            return ResponseDataUtil.buildError("无法获取登陆信息");
        }
    }
}
